package com.yuw.control.userinfo;

import com.alibaba.fastjson.JSON;
import com.yuw.bean.userinfo.UserInfoBean;
import com.yuw.model.userinfo.ModelUserInfo;
import com.yuw.utils.MyUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "ServletUserInfoSave", value = "/ServletUserInfoSave")
public class ServletUserInfoSave extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        UserInfoBean userInfoBean = MyUtils.convertRequest2Bean(request, UserInfoBean.class);
        // 调用model层进行业务逻辑处理
        // 为了测试，避免添加垃圾数据，短路处理，个人调试放开
        int i = MyUtils.getNewInstance(ModelUserInfo.class).saveOrUpdateUserinfo(userInfoBean);

        // 将操作结果保存到map中
        Map mapResult = new HashMap();
        // 记录结果条数
        mapResult.put("result", i);
        // 记录结果状态
        mapResult.put("msg", i == 1 ? "ok" : "ng");

        // 把结果map转换为json字符串
        String strJson = JSON.toJSONString(mapResult);

        // 响应ajax请求
        // 使用response将ajax响应的内容以字节流的形式发回客户端
        PrintWriter printWriter = response.getWriter();
        // 写出数据流
        printWriter.write(strJson);
        // 清空数据流
        printWriter.flush();
    }
}
